package com.example.service.impl;

import com.example.model.Promotion;
import com.example.service.PromotionCacheService;
import org.redisson.api.RBatch;
import org.redisson.api.RScoredSortedSet;
import org.redisson.api.RScoredSortedSetAsync;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PromotionCacheServiceImpl implements PromotionCacheService {
    
    private static final String SKU_PREFIX = "promo:sku:";
    private static final String LABEL_PREFIX = "promo:label:";
    
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void batchBuildCache(List<Promotion> promotions) {
        RBatch batch = redissonClient.createBatch();
        
        try {
            promotions.forEach(promotion -> {
                // 为每个SKU添加活动ID
                promotion.getSkus().forEach(sku -> {
                    RScoredSortedSetAsync<String> set = batch.getScoredSortedSet(SKU_PREFIX + sku);
                    set.addAsync(System.currentTimeMillis(), promotion.getId());
                });
                
                // 为每个标签添加活动ID
                promotion.getSkuLabels().forEach(label -> {
                    RScoredSortedSetAsync<String> set = batch.getScoredSortedSet(LABEL_PREFIX + label);
                    set.addAsync(Double.parseDouble(promotion.getId()), String.valueOf(System.currentTimeMillis()));
                });
            });
            
            // 执行批量操作(事务性)
            batch.execute().getResponses();
        } catch (Exception e) {
            batch.discard();
            throw new RuntimeException("批量构建缓存失败", e);
        }
    }

    @Override
    public Map<String, List<String>> batchQueryPromotions(List<String> skus, List<String> skuLabels) {
        RBatch batch = redissonClient.createBatch();
        
        // 准备批量查询
        skus.forEach(sku -> 
            batch.getScoredSortedSet(SKU_PREFIX + sku).readAllAsync()
        );
        
        skuLabels.forEach(label -> 
            batch.getScoredSortedSet(LABEL_PREFIX + label).readAllAsync()
        );
        
        // 执行批量查询并处理结果
        List<Set<String>> results = (List<Set<String>>) batch.execute()
            .getResponses()
            .stream()
            .map(r -> (Set<String>) r)
            .collect(Collectors.toList());
        
        // 构建返回结果
        Map<String, List<String>> promotionMap = new HashMap<>();
        
        // 处理SKU查询结果
        for (int i = 0; i < skus.size(); i++) {
            promotionMap.put(skus.get(i), new ArrayList<>(results.get(i)));
        }
        
        // 处理标签查询结果
        for (int i = 0; i < skuLabels.size(); i++) {
            promotionMap.put(skuLabels.get(i), new ArrayList<>(results.get(skus.size() + i)));
        }
        
        return promotionMap;
    }
}